<template>

	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>文章管理</el-breadcrumb-item>
	</el-breadcrumb>
	<!-- 搜索框 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
		<el-form-item label="文章名">
			<el-input v-model="queryInfo.articleName" placeholder="请输入文章名" clearable @clear="queryDataList" />
		</el-form-item>
		<el-form-item label="咨询师作者">
			<el-select v-model="queryInfo.counselorId" placeholder="请选择咨询师作者" clearable @clear="queryDataList">
				<el-option v-for="item in counselorList" :key="item.id" :label="item.counselorName" :value="item.id" />
			</el-select>
		</el-form-item>
		<el-form-item label="选择分类">
			<el-select v-model="queryInfo.classifyId" placeholder="请选择分类" clearable @clear="queryDataList">
				<el-option v-for="item in artClassifyList" :key="item.id" :label="item.classifyName" :value="item.id" />
			</el-select>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" size="large" @click="queryDataList">搜索</el-button>
			<el-button type="primary" size="large" @click="add">新增</el-button>
			<!-- 	<el-button type="danger" size="large" @click="batchremove">批量删除</el-button> -->
		</el-form-item>
	</el-form>

	<!-- 表格 -->
	<el-table :data="dataList" border style="width: 100%" row-key="articleId" @selection-change="handleSelectionChange">
		<el-table-column type="selection" width="55" />
		<el-table-column prop="id" label="ID" width="" align="center"></el-table-column>
		<el-table-column prop="articleName" label="文章名" align="center"></el-table-column>
		<el-table-column prop="intro" label="文章简介" align="center"></el-table-column>
		<el-table-column prop="counselor.counselorName" label="咨询师名" align="center"></el-table-column>
		<el-table-column prop="briefImageUrl" label="缩略图" width="200">
			<template #default="scope">
				<img :src="'http://localhost:8080' + scope.row.briefImageUrl" alt="加载失败"
					style="width: 100px; height: 100px; border: 1px solid #f5f7fa; background-color: #f5f7fa">
			</template>
		</el-table-column>


		<el-table-column prop="readNumber" label="阅读量" align="center"></el-table-column>
		<el-table-column prop="articleClassify.classifyName" label="所属分类" align="center"></el-table-column>
		<el-table-column prop="createTime" label="创建时间" align="center" width="200px"></el-table-column>
		<el-table-column label="审核状态" align="center">
			<template #default="scope">
				<el-tag :type="scope.row.status === 0 ? 'info' : 
		             scope.row.status === 1 ? 'success' : 
		             scope.row.status === 2 ? 'danger' : 'info'">
					{{ scope.row.status === 0 ? '审核中' : 
		         scope.row.status === 1 ? '已通过' : 
		         scope.row.status === 2 ? '未通过' : '未知' }}
				</el-tag>
			</template>
		</el-table-column>
		<el-table-column label="状态" align="center">
			<template #default="scope">
				<el-tag :type="scope.row.del === 0 ? 'success' : 'danger'">
					{{ statusMap[scope.row.del] }}
				</el-tag>
			</template>
		</el-table-column>
		<el-table-column label="操作" width="300" align="center">
			<template #default="scope">
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
				<el-button type="primary" size="small" @click="show(scope.row.content)">查看详细内容</el-button>
				<el-button type="warning" size="small" @click="openAuditDialog(scope.row)">审核</el-button>
			</template>
		</el-table-column>
	</el-table>

	<div class="demo-pagination-block">
		<div class="demonstration"></div>
		<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
			:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
			@size-change="handleSizeChange" @current-change="handleCurrentChange" />
	</div>
	<!-- 审核弹窗 -->
	<el-dialog :title="`审核文章：${currentArticle.articleName || ''}`" v-model="auditDialogVisible" width="950px">
		<div class="audit-content">
			<h3 style="margin-bottom: 15px;">文章内容预览：</h3>
			<Editor v-model="currentArticle.content" api-key="xd3env9x2gzjdo6ceaxvt31icnchvb8l681otf3u6ogprz04"
				:init="editorConfig" disabled />
		</div>
		<template #footer>
			<el-button @click="auditDialogVisible = false">取消</el-button>
			<el-button type="success" @click="handleAudit(1)">通过</el-button>
			<el-button type="danger" @click="handleAudit(2)">未通过</el-button>
		</template>
	</el-dialog>
	<el-dialog :title="title" v-model="dialogFormVisible" width="850" @close="cancle">
		<el-form :model="articleData" label-width="100">
			<el-form-item label="文章名">
				<el-input v-model="articleData.articleName" autocomplete="off" placeholder="文章名"></el-input>
			</el-form-item>
			<el-form-item label="文章简介">
				<el-input v-model="articleData.intro" placeholder="请输入文章简介"></el-input>
			</el-form-item>
			<el-form-item label="咨询师作者">
				<el-select v-model="articleData.counselorId" placeholder="请选择咨询师作者" clearable>
					<el-option v-for="item in counselorList" :key="item.id" :label="item.counselorName"
						:value="item.id" />
				</el-select>
			</el-form-item>
			<!-- 新增：文章图片上传 -->
			<!--  <el-form-item label="缩略图" :label-width="formLabelWidth">
		        <el-upload
		            action="http://localhost:8080/upload"
		            list-type="picture-card"
		            :on-success="handleSuccess"
		            :limit="1"
		            :on-preview="handlePictureCardPreview"
		            :file-list="fileList"
		            :on-remove="handleRemove"
		        >
		          <el-icon style="width: 128px; height: 128px; border: 1px dashed #DCDFE6; border-radius: 5px; font-size: 20px;">
		            <Plus />
		          </el-icon>
		        </el-upload>
		        <el-dialog v-model="dialogVisible">
		          <img :src="dialogImageUrl" alt="预览图片" style="width: 100%" />
		        </el-dialog>
		      </el-form-item>
 -->


			<el-form-item label="文章内容详情" prop="content">
				<Editor v-model="articleData.content" api-key="xd3env9x2gzjdo6ceaxvt31icnchvb8l681otf3u6ogprz04"
					:init="editorConfig" />
			</el-form-item>

			<el-form-item label="所属分类">
				<el-select v-model="articleData.articleClassifyId" placeholder="请选择分类" clearable>
					<el-option v-for="item in artClassifyList" :key="item.id" :label="item.classifyName"
						:value="item.id" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">
					确 定
				</el-button>
			</div>
		</template>
	</el-dialog>
	<el-dialog :title="title" v-model="dialogFormVisible1" width="950px">
		<Editor v-model="detailContent" api-key="xd3env9x2gzjdo6ceaxvt31icnchvb8l681otf3u6ogprz04" :init="editorConfig"
			disabled />
		<template #footer>
			<el-button @click="dialogFormVisible1 = false">关闭</el-button>
		</template>
	</el-dialog>


</template>
<script setup>
	import {
		reactive,
		ref,
		getCurrentInstance,
		onMounted
	} from 'vue';

	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	import {
		Plus
	} from '@element-plus/icons-vue'

	// 修改后
	// import { UploadProps, UploadUserFile } from 'element-plus'  
	import Editor from '@tinymce/tinymce-vue'

	const total = ref(0)

	const queryInfo = reactive({
		id: '',
		articleName: '',
		intro: '',
		counselorId: '',
		classifyId: '',
		content: '',
		counselorName: '',
		briefImageUrl: '',
		pageNum: 1,
		pageSize: 5
	})

	const restatusMap = {
		0: '审核中',
		1: '已审核',
	};

	const statusMap = {
		0: '正常',
		1: '异常',
	};
	// 新增：图片上传相关
	/* const dialogImageUrl = ref('')
	const dialogVisible = ref(false)
	const fileList = ref([]) */

	const dataList = ref([])
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;

	// 审核相关变量
	const auditDialogVisible = ref(false);
	const currentArticle = ref({});

	// 打开审核弹窗
	const openAuditDialog = (row) => {
		// 深拷贝当前行数据，避免修改原数据
		currentArticle.value = JSON.parse(JSON.stringify(row));
		auditDialogVisible.value = true;
	};

	// 处理审核结果
	// 处理审核结果（修改后）
	const handleAudit = (status) => {
		if (!currentArticle.value.id) {
			ElMessage.error('文章信息异常，无法审核');
			return;
		}

		// 准备审核参数（JSON格式：包含id和status）
		const auditParams = {
			id: currentArticle.value.id, // 文章ID
			status: status // 1-通过，2-未通过（根据后端需求调整）
		};


		// 发送审核请求（地址：http://localhost:8080/article，方法：PUT，携带JSON参数）
		axios.put('article', auditParams)
			.then(resp => {
				ElMessage.closeAll(); // 关闭加载提示
				if (resp.code === 200) {
					ElMessage.success(status === 1 ? '审核通过' : '已标记为未通过');
					auditDialogVisible.value = false; // 关闭弹窗
					queryDataList(); // 刷新列表数据
				} else {
					ElMessage.error(`审核失败：${resp.msg || '服务器异常'}`);
				}
			})
			.catch(error => {
				ElMessage.closeAll();
				ElMessage.error('网络错误，审核请求发送失败');
				console.error('审核请求错误：', error);
			});
	};


	// 新增：图片上传成功处理
	/* const handleSuccess = (res, file) => {
	  console.log("图片上传成功", res)
	  form.value.briefImageUrl = res.data // 保存图片路径到表单（对应后端字段）
	  // 更新fileList以显示已上传的图片
	  fileList.value = [{ url: `http://localhost:8080${res.data}` }]
	}

	// 新增：移除图片处理
	const handleRemove = (file, fileList) => {
	  form.value.simplifyImage = '' // 清空表单中的图片路径
	}

	// 新增：图片预览处理
	const handlePictureCardPreview = (file) => {
	  dialogImageUrl.value = file.url
	  dialogVisible.value = true
	} */

	// 新增：图片上传前校验
	/* const beforeAvatarUpload = (rawFile) => {
	  const isJPG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
	  const isLt2M = rawFile.size / 1024 / 1024 < 2

	  if (!isJPG) {
	    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
	  }
	  if (!isLt2M) {
	    ElMessage.error('上传图片大小不能超过 2MB!')
	  }
	  return isJPG && isLt2M
	} */

	const queryDataList = () => {
		axios.get('article/page', {
			params: queryInfo
		}).then((resp) => {
			if (resp.code == 200) {
				dataList.value = resp.data.list;
				total.value = resp.data.total;
			} else {
				ElMessage.error('查询失败')
			}
		})
	}



	const editorConfig = {
		height: 500,
		menubar: true,
		plugins: 'lists link image table code help',
		toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright | bullist numlist | removeformat',
		skin: 'oxide', // 可选：'oxide-dark' 暗黑模式
		content_css: 'default' // 可选：'dark' 暗黑模式
	}


	const counselorList = ref([])


	const queryCounselorList = () => {
		axios.get('counselor', {
			// params: counselorInfo
		}).then((resp) => {
			if (resp.code == 200) {
				console.log('咨询师接口响应:', resp.data);
				counselorList.value = resp.data;
			} else {
				ElMessage.error('查询失败')
			}
		})
	}

	const artClassifyList = ref([])

	const queryartClassifyList = () => {
		axios.get('articleClassify', {

		}).then((resp) => {
			if (resp.code == 200) {
				console.log('咨询师接口响应:', resp.data);
				artClassifyList.value = resp.data;
			} else {
				ElMessage.error('查询失败')
			}
		})
	}


	const title = ref()
	const dialogFormVisible = ref(false)


	onMounted(() => {
		queryDataList()
		queryCounselorList()
		queryartClassifyList()
	})

	const handleSizeChange = (val) => {
		queryDataList()
	}

	const handleCurrentChange = (val) => {
		queryDataList()
	}

	const articleData = ref({
		id: '',
		articleName: '',
		intro: '',
		counselorId: '',
		classifyId: '',
		content: '',
		counselorName: '',
		briefImageUrl: '',
		status: 0,
		del: 0
	})

	const add = () => {
		title.value = '新增'
		dialogFormVisible.value = true
	}

	const cancle = () => {
		console.log('你点击了取消按钮');
		articleData.value = {
			articleName: '',
			intro: '',
			counselorName: '',
			briefImageUrl: '',
			content: '',
			classifyName: ''

		}
		dialogFormVisible.value = false
	}

	const confirm = () => {
		if (articleData.value.id) {
			console.log('你点击了确定按钮');
			axios.put('article', articleData.value)
				.then((resp) => {
					if (resp.code == 200) {
						ElMessage({
							message: '修改成功',
							type: 'success',
						})
					} else {
						ElMessage.error('修改失败')
					}
					queryDataList()
					dialogFormVisible.value = false
				})
		} else {
			console.log('你点击了确定按钮');
			axios.post('article', articleData.value)
				.then((resp) => {
					if (resp.code == 200) {
						ElMessage({
							message: '新增成功',
							type: 'success',
						})
					} else {
						ElMessage.error('新增失败')
					}
					queryDataList()
					dialogFormVisible.value = false
				})
		}
	}

	const edit = (row) => {
		console.log(row);
		title.value = '编辑'
		dialogFormVisible.value = true
		row.articleName = row.articleName + ''
		row.intro = row.intro + ''
		row.counselorName = row.counselorName + ''
		row.briefImageUrl = row.briefImageUrl + ''
		row.content = row.content + ''
		row.classifyName = row.classifyName + ''
		articleData.value = row
		/* if (row.briefImageUrl) {
		    fileList.value = [
		      {
		        url: `http://localhost:8080/upload${row.briefImageUrl}`, // 完整图片路径
		        name: '已上传图片', // 显示的文件名
		        status: 'success' // 标记为已上传状态
		      }
		    ];
		  } else {
		    fileList.value = []; // 无图片时清空
		  } */
	}

	const remove = (articleId) => {
		console.log(articleId);
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			).then(() => {
				axios.delete(`article/${articleId}`)
					.then((resp) => {
						if (resp.code == 200) {
							ElMessage.success('删除成功')
						} else {
							ElMessage.error('删除失败')
						}
						queryDataList()
					})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '已取消删除',
				})
			})
	}

	const multipleSelection = ref([]);

	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.articleId
		})
		console.log(multipleSelection.value);
	}

	const batchremove = () => {
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			).then(() => {
				axios.delete(`article`, {
						params: {
							ids: multipleSelection.value.join(',')
						}
					})
					.then((resp) => {
						if (resp.code == 200) {
							ElMessage.success('删除成功')
						} else {
							ElMessage.error('删除失败')
						}
						queryDataList()
					})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '已取消删除',
				})
			})
	}

	const detailContent = ref('');
	const dialogFormVisible1 = ref(false)

	const show = (content) => {
		detailContent.value = content;
		dialogFormVisible1.value = true;
	}
</script>

<style scoped>
	.el-breadcrumb {
		margin-bottom: 15px;
		padding: 0 0 15px;
		border-bottom: 1px solid #ddd;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	.demo-pagination-block .demonstration {
		margin-bottom: 16px;
	}

	.el-table {
		line-height: 40px;
	}

	/* 新增：图片上传样式优化 */
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}
</style>